package com.crealth.db;

import java.util.ArrayList;
import java.util.List;

import com.crealth.manager.MybatisManager;
import com.crealth.memcached.CompanyCached;
import com.crealth.model.CompanyModel;
import com.crealth.utils.StringUtil;

public class CompanyDb {

	public static List<CompanyModel> selectAllCompany() {
		List<CompanyModel> companyls = MybatisManager.companyMapper.selectAllCompany();
	
		return companyls;
	}
	
	public static void insertBranch(CompanyModel company) {
		MybatisManager.companyMapper.insertBranch(company);
		MybatisManager.commit();
	}
	
	public static CompanyModel selectCompanyByID(int companyID) {
		CompanyModel topCompany = MybatisManager.companyMapper.selectCompanyByID(companyID);
		
		return topCompany;
	}
	
	public static List<CompanyModel> selectDepartmentByID(int companyID) {
		List<CompanyModel> companyls = MybatisManager.companyMapper.selectDepartmentByID(companyID);
		
		return companyls;
	}
	
	public static List<Integer> selectDepartmentIDByID(int companyID) {
		List<Integer> departls = MybatisManager.companyMapper.selectDepartmentIDByID(companyID);
		
		return departls;
	}
	
	public static List<CompanyModel> selectSubCompanyByID(int companyID) {
		List<CompanyModel> companyls = MybatisManager.companyMapper.selectSubCompanyByID(companyID);
		
		return companyls;
	}
	
	public static Integer updateCompanyInfo(CompanyModel company) {
		Integer res = MybatisManager.companyMapper.updateCompanyInfo(company);
		MybatisManager.commit();
		
		return res;
	}
	
	public static Integer deleteCompanyByID(int companyID) {
		Integer res = MybatisManager.companyMapper.deleteCompanyByID(companyID);
		MybatisManager.commit();
		
		return res;
	}
	
	public static int getTopCompanyID(int companyID) {
		CompanyModel company = CompanyCached.selectCompanyByID(companyID);
		if (company == null) {
			return 0;
		}
		int superCompanyID = company.getSuperCompanyID();
		if (superCompanyID <= 0) {
			return companyID;
		}
		while (true) {
			return getTopCompanyID(superCompanyID);
		}
	}
	
	// 获取所在公司 companyID  可能是部门ID
	public static CompanyModel getCompanyByID(int companyID) {
		CompanyModel company = CompanyCached.selectCompanyByID(companyID);
		if (company == null) {
			return null;
		}
		if (company.getCompanyAddr() != null &&
				company.getCompanyAddr().length() > 0) {
			return company;
		}
		int superCompanyID = company.getSuperCompanyID();
		company = CompanyCached.selectCompanyByID(superCompanyID);
		return company;
	}
	
	public static String getDepartmentIDs(int companyID, boolean containCom) {
		List<Integer> idls = selectDepartmentIDByID(companyID);
		if (containCom) {
			if (idls == null) {
				idls = new ArrayList<Integer>();
			}
			idls.add(companyID);
		}
				
		String strIDs = StringUtil.mergeListIntegerToString(idls, ",");
		return strIDs;
	}
	
}
